package controllers

import (
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
)

type WsController struct {
	beego.Controller
}

var clients = make(map[*websocket.Conn](chan string))
var queue = make(chan string)

func init() {
	go HandleMessages()
	go Monitor()
	go BBS()
}

func (c *WsController) Get() {
	header := make(http.Header)
	header["X-ONLINE-DAMAKU"] = []string{"1"}
	ws, err := websocket.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, header, 1024, 1024)
	if nil != err {
		fmt.Println("WebSocket启动失败")
		panic(err)
	}
	clients[ws] = make(chan string)
	ws.SetCloseHandler(func(code int, text string) error {
		fmt.Println("Quit@SetCloseHandler")
		clients[ws] <- "SIGNAL:15"
		delete(clients, ws)
		return nil
	})

	go HandleClient(ws)
	fmt.Println("启动HandleClient")
	defer ws.Close()

	for {
		_, data, err := ws.ReadMessage()
		fmt.Println("接收到消息:", string(data))
		if nil != err {
			fmt.Println("ReadMessageError:", err)
			break
		}
		queue <- string(data)
	}
	// fmt.Println("Quit:", ws)
	// close(clients[ws])

	c.EnableRender = false
}

func HandleMessages() {
	for {
		msg := <-queue
		for client := range clients {
			clients[client] <- msg
		}
	}
}

//
func HandleClient(ws *websocket.Conn) {
	channel := clients[ws]
	for {
		msg := <-channel
		if msg == "SIGNAL:15" {
			fmt.Println("释放资源")
			close(channel)
			return
		}
		err := ws.WriteMessage(websocket.TextMessage, []byte(msg))
		if nil != err {
			fmt.Println(err)
			delete(clients, ws)
			return
		}
	}

}

func Monitor() {
	for {
		fmt.Println("当前在线人数：" + strconv.Itoa(len(clients)))
		time.Sleep(10 * time.Second)
	}
}

func BBS() {
	for {
		msg := "【系统通知】当前在线人数：" + strconv.Itoa(len(clients)) + " 人"
		for ws := range clients {
			err := ws.WriteMessage(websocket.TextMessage, []byte(msg))
			if nil != err {
				fmt.Println("Quit@BBS")
				clients[ws] <- "SIGNAL:15"
				delete(clients, ws)
			}
		}
		time.Sleep(1 * time.Second)
	}
}
